<template>
  <div class="screening-container">
    <!-- 筛选条件 -->
    <el-form :inline="true" class="filter-form">
      <el-form-item label="统计时间">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item label="医疗机构">
        <el-select v-model="filter.hospital" placeholder="请选择" clearable>
          <el-option
            v-for="org in orgOptions"
            :key="org"
            :label="org"
            :value="org"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="业务类型">
        <el-radio-group v-model="filter.businessType">
          <el-radio-button label="筛查" />
          <el-radio-button label="门诊" />
          <el-radio-button label="随访" />
        </el-radio-group>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 汇总数据 -->
    <el-row :gutter="20" class="summary-row">
      <el-col :span="4" v-for="(item, index) in summaryData" :key="index">
        <div
          class="summary-card"
          :style="{ backgroundColor: index === 0 ? '#f5fbff' : '#fff' }"
        >
          <div class="title">{{ item.title }}</div>
          <div
            class="value"
            :style="{ color: index === 0 ? '#1890ff' : '#333' }"
          >
            {{ item.value }}
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-table
      :data="processedTableData"
      border
      style="width: 100%"
      class="data-table"
      v-loading="loading"
      :row-style="{ height: '60px' }"
    >
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="orgName" label="机构/家医团队" width="220" fixed />
      <el-table-column prop="total" label="筛查总数" align="center" />
      <el-table-column prop="hypertension" label="高血压筛查" align="center" />
      <el-table-column prop="diabetes" label="高血糖筛查" align="center" />
      <el-table-column prop="obesity" label="肥胖筛查" align="center" />
    </el-table>

    <!-- 分页 -->
    <el-pagination
      class="pagination"
      :current-page="pagination.current"
      :page-size="pagination.size"
      :total="pagination.total"
      :page-sizes="[10, 20, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';

const apiUrl = import.meta.env.VITE_APP_API_URL;
// 筛选条件
const dateRange = ref([]);
const filter = reactive({
  hospital: '',
  businessType: '筛查'
});

// 分页参数
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
});

// 加载状态
const loading = ref(false);

// 原始数据
const rawData = ref([]);
const orgOptions = ref([]);

// 处理后的表格数据
const processedTableData = computed(() => {
  const orgMap = new Map();

  rawData.value.forEach((item) => {
    if (!orgMap.has(item.orgName)) {
      orgMap.set(item.orgName, {
        orgName: item.orgName,
        total: 0,
        hypertension: 0,
        diabetes: 0,
        obesity: 0
      });
    }

    const org = orgMap.get(item.orgName);

    // 计算每个指标（直接累加）
    const hasHypertension = item.hypertension === 1 ? 1 : 0;
    const hasDiabetes = item.diabetes === 1 ? 1 : 0;
    const hasObesity = item.bmi >= 28 ? 1 : 0;

    // 更新机构数据
    org.hypertension += hasHypertension;
    org.diabetes += hasDiabetes;
    org.obesity += hasObesity;

    // 总筛查数 = 高血压 + 高血糖 + 肥胖（允许重复计算）
    org.total += hasHypertension + hasDiabetes + hasObesity;
  });

  return Array.from(orgMap.values()).map((org) => ({
    ...org,
    // 保留原始数据用于汇总
    _total: org.total
  }));
});

// 汇总数据
const summaryData = computed(() => {
  const totals = processedTableData.value.reduce(
    (acc, cur) => ({
      total: acc.total + cur.total,
      hypertension: acc.hypertension + cur.hypertension,
      diabetes: acc.diabetes + cur.diabetes,
      hyperlipidemia: acc.hyperlipidemia + cur.hyperlipidemia,
      obesity: acc.obesity + cur.obesity,
      uricAcid: acc.uricAcid + cur.uricAcid
    }),
    {
      total: 0,
      hypertension: 0,
      diabetes: 0,
      hyperlipidemia: 0,
      obesity: 0,
      uricAcid: 0
    }
  );

  return [
    { title: '筛查总人数', value: totals.total },
    { title: '高血压筛查', value: totals.hypertension },
    { title: '高血糖筛查', value: totals.diabetes },
    { title: '肥胖筛查', value: totals.obesity }
  ];
});

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true;
    const url = new URL(apiUrl + '/T7/Medical/ManagementhierarchyQuery');
    // 安全处理日期参数
    const getSafeDate = (index) => {
      // 使用可选链和空值判断
      if (!dateRange.value || dateRange.value.length < index + 1)
        return undefined;
      const dateStr = dateRange.value[index];
      return dateStr
        ? `${dateStr}T${index === 0 ? '00:00:00' : '23:59:59'}`
        : undefined;
    };
    // 添加查询参数
    const params = {
      PageIndex: pagination.current,
      PageSize: pagination.size,
      OrgName: filter.hospital || undefined,
      Hypertension: filter.businessType === '筛查' ? 1 : undefined,
      Diabetes: filter.businessType === '筛查' ? 1 : undefined,
      StartTime: getSafeDate(0),
      EndTime: getSafeDate(1)
    };

    // 添加有效参数到URL
    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined) {
        url.searchParams.append(key, value);
      }
    });

    const response = await fetch(url);
    const data = await response.json();
    rawData.value = data.list;
    pagination.total = data.totalCount;

    // 生成机构选项
    orgOptions.value = [...new Set(data.list.map((item) => item.orgName))];
    // ...保持原有数据处理逻辑不变
  } catch (error) {
    console.error('数据获取失败:', error);
  } finally {
    loading.value = false;
  }
};

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size;
  fetchData();
};

const handlePageChange = (page) => {
  pagination.current = page;
  fetchData();
};

// 查询处理
const handleQuery = () => {
  pagination.current = 1;
  fetchData();
};

// 重置筛选
const handleReset = () => {
  dateRange.value = [];
  filter.hospital = '';
  filter.businessType = '筛查';
  pagination.current = 1;
  fetchData();
};

// 初始化加载
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.screening-container {
  padding: 20px;
  background: #fff;
}

.filter-form {
  margin-bottom: 20px;

  :deep(.el-form-item) {
    margin-bottom: 15px;
  }
}

.summary-row {
  margin: 20px 0;

  .summary-card {
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    padding: 15px;
    text-align: center;

    .title {
      color: #666;
      margin-bottom: 8px;
    }

    .value {
      font-size: 24px;
      font-weight: 500;
    }
  }
}

.data-table {
  margin-top: 20px;

  :deep(th) {
    background-color: #fafafa;
  }
}

.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.el-date-editor {
  width: 350px;
}

.el-select {
  width: 180px;
}
</style>
